import mongoose from 'mongoose';
import bcrypt from 'bcryptjs';

// 定义用户Schema
const userSchema = new mongoose.Schema({
  username: {
    type: String,
    required: true,
    unique: true,
    trim: true,
    lowercase: true,
    minlength: 3,
    maxlength: 50
  },
  password: {
    type: String,
    required: true,
    minlength: 6
  },
  createdAt: {
    type: Date,
    default: Date.now
  },
  updatedAt: {
    type: Date,
    default: Date.now
  }
});

// 密码加密中间件
userSchema.pre('save', async function(next) {
  // 只有当密码被修改时才重新加密
  if (!this.isModified('password')) {
    return next();
  }
  
  try {
    // 加密密码
    const salt = await bcrypt.genSalt(10);
    this.password = await bcrypt.hash(this.password, salt);
    next();
  } catch (error) {
    next(error);
  }
});

// 验证密码的方法
userSchema.methods.validatePassword = async function(password) {
  return bcrypt.compare(password, this.password);
};

// 转换为JSON时排除密码字段
userSchema.methods.toJSON = function() {
  const user = this.toObject();
  delete user.password;
  return user;
};

// 静态方法：根据用户名查找用户
userSchema.statics.findByUsername = async function(username) {
  return this.findOne({ username });
};

// 静态方法：创建新用户
userSchema.statics.create = async function(username, password) {
  // 检查用户是否已存在
  const existingUser = await this.findOne({ username });
  if (existingUser) {
    throw new Error('用户已存在');
  }
  
  // 创建新用户
  const user = new this({ username, password });
  await user.save();
  return user;
};

// 创建User模型
const User = mongoose.model('User', userSchema);

export default User;